package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yuoj.annotation.AuthCheck;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.constant.UserConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.entity.MemberLevels;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.service.MemberLevelsService;
import com.yupi.yuoj.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 会员等级接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/member-levels")
@Slf4j
public class MemberLevelsController {

    @Resource
    private MemberLevelsService memberLevelsService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建会员等级
     *
     * @param memberLevels
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addMemberLevel(@RequestBody MemberLevels memberLevels, HttpServletRequest request) {
        if (memberLevels == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        // 校验必填字段
        String levelCode = memberLevels.getLevelCode();
        String levelName = memberLevels.getLevelName();
        if (levelCode == null || levelCode.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "等级代码不能为空");
        }
        if (levelName == null || levelName.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "等级名称不能为空");
        }
        
        User loginUser = userService.getLoginUser(request);
        
        // 设置默认值
        if (memberLevels.getIsActive() == null) {
            memberLevels.setIsActive(1);
        }
        
        boolean result = memberLevelsService.save(memberLevels);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newMemberLevelId = memberLevels.getId().longValue();
        return ResultUtils.success(newMemberLevelId);
    }

    /**
     * 删除会员等级
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteMemberLevel(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        MemberLevels oldMemberLevel = memberLevelsService.getById(id);
        ThrowUtils.throwIf(oldMemberLevel == null, ErrorCode.NOT_FOUND_ERROR);
        boolean b = memberLevelsService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新会员等级（仅管理员）
     *
     * @param memberLevels
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateMemberLevel(@RequestBody MemberLevels memberLevels, HttpServletRequest request) {
        if (memberLevels == null || memberLevels.getId() == null || memberLevels.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "ID不能为空");
        }
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        MemberLevels oldMemberLevel = memberLevelsService.getById(memberLevels.getId());
        ThrowUtils.throwIf(oldMemberLevel == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = memberLevelsService.updateById(memberLevels);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取会员等级
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<MemberLevels> getMemberLevelById(@RequestParam long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        MemberLevels memberLevel = memberLevelsService.getById(id);
        if (memberLevel == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(memberLevel);
    }

    /**
     * 分页获取会员等级列表（仅管理员）
     *
     * @param current
     * @param size
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<MemberLevels>> listMemberLevelByPage(@RequestParam long current, @RequestParam long size) {
        Page<MemberLevels> memberLevelPage = memberLevelsService.page(new Page<>(current, size));
        return ResultUtils.success(memberLevelPage);
    }

    /**
     * 分页获取公开的会员等级列表
     *
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<MemberLevels>> listPublicMemberLevels(
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        
        Page<MemberLevels> memberLevelPage = memberLevelsService.page(new Page<>(current, size));
        return ResultUtils.success(memberLevelPage);
    }

    /**
     * 获取所有启用的会员等级
     *
     * @return
     */
    @GetMapping("/list/active")
    public BaseResponse<Page<MemberLevels>> listActiveMemberLevels() {
        Page<MemberLevels> memberLevelPage = memberLevelsService.lambdaQuery()
                .eq(MemberLevels::getIsActive, 1)
                .orderByAsc(MemberLevels::getMinExp)
                .page(new Page<>(1, 100));
        return ResultUtils.success(memberLevelPage);
    }

    /**
     * 编辑会员等级（给用户使用）
     *
     * @param memberLevels
     * @param request
     * @return
     */
    @PostMapping("/edit")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> editMemberLevel(@RequestBody MemberLevels memberLevels, HttpServletRequest request) {
        if (memberLevels == null || memberLevels.getId() == null || memberLevels.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "ID不能为空");
        }
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        MemberLevels oldMemberLevel = memberLevelsService.getById(memberLevels.getId());
        ThrowUtils.throwIf(oldMemberLevel == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = memberLevelsService.updateById(memberLevels);
        return ResultUtils.success(result);
    }

    // endregion
}